

import CreativeComponent from '../index';
import BaseComponent from '../../component';
import { MAIN_JUMP_INFO } from '../../helper';
// 将广点通给的组件列表从拍平状改造为树状
function useAntiFlat(tx_creative_components: Array<any>, props = {
  // 橱窗 是否
  useShowcase: false,
}) {
  function buildTree(arr: any, parent = null) {
    const isRoot = !parent;
    let result: any = parent ? {} : [];
    const sonArr = arr.filter((v: any) => parent === null ? !v.parent_name : v.parent_name === parent);
    for (const val of sonArr) {
      const children = buildTree(arr, val.name);
      if (children) {
        val.children = children;
      }
      !isRoot ? (result[val.name] = val) : result.push(val);
    }
    return result;
  }
  const recreative_components = buildTree(tx_creative_components)
  console.info('创意组件list:', recreative_components);
  let new_recreative_components = [];
  if (props.useShowcase) {
    let mediaList = undefined;
    let media = undefined;
    let showcaseName = 'image_showcase';
    let type = 'image';
    // 针对橱窗类的组件 由于 广点通要求上传为xx_showcase类的组件，但是模板中并不返回xx_showcase，只返回image+image_list组件，这边前端手动判定融合
    /**
     *  [{ name: 'image_list' }, { name: 'image' }] => [{ name: 'image_showcase', children: { image_list: { name: 'image_list' }, image: { name: 'image' } }}]
     *
     *
     */
    const hasShowcase = recreative_components.find((component: any) => {
      const name = component.name;
      if (name == 'image' || name == 'video') {
        media = component;
        showcaseName = name == 'image' ? 'image_showcase' : 'video_showcase';
        type = name == 'image' ? 'image' : 'video';
      }
      else if (name == 'image_list') {

        mediaList = component;
      }
      else {
        new_recreative_components.push(component)
      }
      return name === 'image_showcase' || name === 'video_showcase';
    });
    if (!hasShowcase) {
      new_recreative_components.push({
        name: showcaseName,
        required: true,
        array_property: { min_number: 1, max_number: 1 },
        element_type: "ELEMENT_TYPE_STRUCT",
        field_type: "FIELD_TYPE_STRUCT_ARRAY",
        description: '橱窗',
        children: {
          ['image_list']: mediaList,
          [type]: media
        }
      })
    } else {
      new_recreative_components = recreative_components;
    }

  } else {
    new_recreative_components = recreative_components;
  }
  return new_recreative_components;
}
// 使用组件
function useConstructor(componentOptions: any) {
  let name = componentOptions.tx_component;
  const _constructor = (CreativeComponent as any)[name] || BaseComponent;
  const component = new _constructor({
    ...componentOptions,
    tx_component: name,
    type: name,
  });
  return component;
}

export {
  useConstructor,
  useAntiFlat
}
